package models

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

// ClaimsExtended 用于表示解密后的Claims内容
type ClaimsExtended map[string]interface{}

// Roselove 解析和验证JWT Token
func CheckId(tsy string) (*ClaimsExtended, error) {
	// 解析Token字符串
	token, err := jwt.Parse(tsy, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte("scriptKill"), nil // 确保这是正确的密钥
	})

	if err != nil {
		return nil, err
	}

	// 确保Token是有效的
	if !token.Valid {
		return nil, fmt.Errorf("token is invalid")
	}

	// 从Token中提取Claims
	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		return nil, fmt.Errorf("error casting claims to MapClaims")
	}

	// 创建ClaimsExtended的副本
	decryptedClaims := make(ClaimsExtended)

	for key, value := range claims {
		decryptedClaims[key] = value
	}

	// 检查Token是否过期
	expiry := int64(claims["exp"].(float64))
	now := time.Now().Unix()
	if expiry < now {
		return &decryptedClaims, fmt.Errorf("token has expired")
	}

	// 返回解密的Claims内容
	return &decryptedClaims, nil
}
